/**
 * 数据覆盖机制集成测试
 * 
 * 测试APK每秒向服务端发送数据并获得批量带时间戳结果的数据覆盖功能
 * 验证新数据能够正确覆盖原先缓存的重复数据
 * 
 * 使用方法：
 * 1. 模拟服务端返回TabletBrainWaveResponse数据
 * 2. 验证数据缓存管理器的覆盖逻辑
 * 3. 测试NeuroSkyService的集成功能
 * 
 * 原理：
 * - 基于时间戳进行数据去重和覆盖
 * - 使用ConcurrentSkipListMap保证线程安全和时间排序
 * - 通过回调机制通知数据更新
 * 
 * 注意：此测试已更新为使用新的TabletBrainWaveResponse模型
 */

import com.example.brain_wave.bluetooth.cache.DataCacheManager
import com.example.brain_wave.api.model.TabletBrainWaveResponse
import com.example.brain_wave.bluetooth.service.NeuroSkyService
import org.junit.Test
import org.junit.Assert.*
import org.junit.Before
import android.content.Context
import androidx.test.core.app.ApplicationProvider

class DataCoverageIntegrationTest {

    private lateinit var dataCacheManager: DataCacheManager
    private lateinit var neuroSkyService: NeuroSkyService

    @Before
    fun setUp() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        dataCacheManager = DataCacheManager(context)
        neuroSkyService = NeuroSkyService(context)
    }

    @Test
    fun testDataCoverageScenario() {
        // 模拟第一次服务端响应
        val firstResponse = TabletBrainWaveResponse(
            success = true,
            message = "数据接收成功",
            sessionId = "test_session_1",
            timestamp = 1000L,
            receivedDataPoints = 256,
            sleepStage = "wake",
            confidence = 0.7f,
            frequencyBands = null,
            analysisDurationMs = 1000,
            bufferSize = 16809,
            yasaAvailable = true
        )

        // 处理第一次响应
        dataCacheManager.processServerResponse(firstResponse)
        assertEquals(1, dataCacheManager.getCacheSize())

        // 模拟第二次服务端响应（包含重复时间戳的新数据）
        val secondResponse = TabletBrainWaveResponse(
            success = true,
            message = "数据更新成功",
            sessionId = "test_session_1",
            timestamp = 1000L, // 相同时间戳，应该覆盖
            receivedDataPoints = 256,
            sleepStage = "light_sleep", // 更新的睡眠阶段
            confidence = 0.8f, // 更新的置信度
            frequencyBands = null,
            analysisDurationMs = 1200,
            bufferSize = 16809,
            yasaAvailable = true
        )

        // 处理第二次响应
        dataCacheManager.processServerResponse(secondResponse)
        assertEquals(1, dataCacheManager.getCacheSize()) // 应该仍然只有1个响应（被覆盖）

        // 验证数据覆盖
        val allResponses = dataCacheManager.getAllDataPoints()
        val responseAt1000 = allResponses.find { it.timestamp == 1000L }
        assertNotNull(responseAt1000)
        assertEquals("light_sleep", responseAt1000!!.sleepStage) // 验证数据被覆盖
        assertEquals(0.8f, responseAt1000.confidence, 0.01f) // 验证置信度被更新

        // 添加新的不同时间戳的响应
        val thirdResponse = TabletBrainWaveResponse(
            success = true,
            message = "新数据",
            sessionId = "test_session_1",
            timestamp = 2000L, // 不同时间戳
            receivedDataPoints = 256,
            sleepStage = "deep_sleep",
            confidence = 0.9f,
            frequencyBands = null,
            analysisDurationMs = 1300,
            bufferSize = 16809,
            yasaAvailable = true
        )

        dataCacheManager.processServerResponse(thirdResponse)
        assertEquals(2, dataCacheManager.getCacheSize()) // 现在应该有2个响应

        // 验证新数据被正确添加
        val responseAt2000 = dataCacheManager.getAllDataPoints().find { it.timestamp == 2000L }
        assertNotNull(responseAt2000)
        assertEquals("deep_sleep", responseAt2000!!.sleepStage)
        assertEquals(0.9f, responseAt2000.confidence, 0.01f)
    }

    @Test
    fun testNeuroSkyServiceIntegration() {
        var dataUpdatedCallbackTriggered = false
        var receivedResponses: List<TabletBrainWaveResponse>? = null

        // 设置服务端数据更新回调
        neuroSkyService.setOnServerDataUpdated { responses ->
            dataUpdatedCallbackTriggered = true
            receivedResponses = responses
        }

        // 验证回调设置成功
        assertTrue("NeuroSkyService应该支持设置服务端数据更新回调", true)
        
        // 验证缓存管理器集成
        assertTrue("NeuroSkyService应该集成DataCacheManager", neuroSkyService.getServerDataCacheSize() >= 0)
    }

    @Test
    fun testCachePerformanceWithLargeDataset() {
        val startTime = System.currentTimeMillis()
        
        // 模拟大量TabletBrainWaveResponse数据
        for (i in 1..1000) {
            val response = TabletBrainWaveResponse(
                success = true,
                message = "大数据集测试 $i",
                sessionId = "performance_test",
                timestamp = startTime + i * 1000L,
                receivedDataPoints = 256,
                sleepStage = if (i % 3 == 0) "wake" else if (i % 3 == 1) "light_sleep" else "deep_sleep",
                confidence = (0.5f + (i % 5) * 0.1f),
                frequencyBands = null,
                analysisDurationMs = 1000 + i,
                bufferSize = 16809,
                yasaAvailable = true
            )
            dataCacheManager.processServerResponse(response)
        }
        
        val endTime = System.currentTimeMillis()
        val processingTime = endTime - startTime

        // 验证处理时间合理（应该在合理时间内完成）
        assertTrue("大数据集处理时间应该合理", processingTime < 5000) // 5秒内完成
        assertEquals(1000, dataCacheManager.getCacheSize())
    }

    @Test
    fun testConcurrentDataUpdates() {
        val threads = mutableListOf<Thread>()
        val baseTime = System.currentTimeMillis()
        
        // 创建多个线程同时更新数据
        repeat(10) { threadIndex ->
            val thread = Thread {
                val response = TabletBrainWaveResponse(
                    success = true,
                    message = "并发测试 $threadIndex",
                    sessionId = "concurrent_test",
                    timestamp = baseTime + (threadIndex * 1000).toLong(),
                    receivedDataPoints = 256,
                    sleepStage = if (threadIndex % 2 == 0) "wake" else "light_sleep",
                    confidence = 0.7f + (threadIndex * 0.02f),
                    frequencyBands = null,
                    analysisDurationMs = 1000 + threadIndex,
                    bufferSize = 16809,
                    yasaAvailable = true
                )
                dataCacheManager.processServerResponse(response)
            }
            threads.add(thread)
        }

        // 启动所有线程
        threads.forEach { it.start() }
        
        // 等待所有线程完成
        threads.forEach { it.join() }

        // 验证数据完整性
        assertEquals(10, dataCacheManager.getCacheSize())
        
        val allResponses = dataCacheManager.getAllDataPoints()
        assertEquals(10, allResponses.size)
        
        // 验证数据按时间戳排序
        val timestamps = allResponses.map { it.timestamp }
        assertEquals(timestamps.sorted(), timestamps)
    }
}